/**
 * 预约管理页面脚本
 */

document.addEventListener('DOMContentLoaded', function() {
    // 初始化变量
    const viewToggleButtons = document.querySelectorAll('.view-toggle .view-btn');
    const calendarView = document.querySelector('.appointments-calendar-view');
    const listView = document.querySelector('.appointments-list-view');
    const prevWeekBtn = document.getElementById('prevWeek');
    const nextWeekBtn = document.getElementById('nextWeek');
    const currentWeekEl = document.getElementById('currentWeek');
    const newAppointmentBtn = document.getElementById('newAppointmentBtn');
    const appointmentModal = document.getElementById('appointmentModal');
    const appointmentItems = document.querySelectorAll('.appointment-item');
    const modalCloseBtn = document.querySelector('.modal-close');
    const dismissBtn = document.querySelector('[data-dismiss="modal"]');
    const saveAppointmentBtn = document.getElementById('saveAppointment');
    const exportBtn = document.getElementById('exportBtn');
    const searchBtn = document.getElementById('searchBtn');
    const statusFilter = document.getElementById('statusFilter');
    const departmentFilter = document.getElementById('departmentFilter');
    const dateFilter = document.getElementById('dateFilter');

    // 当前日期
    let currentDate = new Date();
    let currentView = 'week';

    // 视图切换
    viewToggleButtons.forEach(button => {
        button.addEventListener('click', () => {
            const view = button.getAttribute('data-view');
            
            // 更新按钮状态
            viewToggleButtons.forEach(btn => btn.classList.remove('active'));
            button.classList.add('active');
            
            // 更新视图
            if (view === 'list') {
                calendarView.style.display = 'none';
                listView.style.display = 'block';
                currentView = 'list';
            } else {
                calendarView.style.display = 'block';
                listView.style.display = 'none';
                currentView = view;
                
                // 更新日历视图
                updateCalendarView();
            }
        });
    });

    // 星期导航
    prevWeekBtn.addEventListener('click', () => {
        currentDate.setDate(currentDate.getDate() - 7);
        updateCalendarView();
    });

    nextWeekBtn.addEventListener('click', () => {
        currentDate.setDate(currentDate.getDate() + 7);
        updateCalendarView();
    });

    // 更新日历视图
    function updateCalendarView() {
        // 获取当前周的开始日期（周日）
        const weekStart = new Date(currentDate);
        weekStart.setDate(currentDate.getDate() - currentDate.getDay());
        
        // 更新周标题
        const weekEnd = new Date(weekStart);
        weekEnd.setDate(weekStart.getDate() + 6);
        
        currentWeekEl.textContent = formatDateRange(weekStart, weekEnd);
        
        // 更新每一天的标题
        const dayHeaders = document.querySelectorAll('.calendar-day .day-header');
        dayHeaders.forEach((header, index) => {
            const dayDate = new Date(weekStart);
            dayDate.setDate(weekStart.getDate() + index);
            
            const dayName = header.querySelector('.day-name');
            const dayDateEl = header.querySelector('.day-date');
            
            dayName.textContent = formatDayName(dayDate.getDay());
            dayDateEl.textContent = formatDayDate(dayDate);
            
            // 高亮当天
            const calendarDay = header.closest('.calendar-day');
            if (isSameDay(dayDate, new Date())) {
                calendarDay.classList.add('current-day');
            } else {
                calendarDay.classList.remove('current-day');
            }
        });
    }

    // 点击预约项打开详情模态框
    appointmentItems.forEach(item => {
        item.addEventListener('click', () => {
            openAppointmentModal(item);
        });
    });

    // 打开新建预约模态框
    newAppointmentBtn.addEventListener('click', () => {
        openAppointmentModal();
    });

    // 关闭模态框
    [modalCloseBtn, dismissBtn].forEach(btn => {
        if (btn) {
            btn.addEventListener('click', () => {
                closeAppointmentModal();
            });
        }
    });

    // 点击模态框外部关闭模态框
    appointmentModal.addEventListener('click', (event) => {
        if (event.target === appointmentModal) {
            closeAppointmentModal();
        }
    });

    // 保存预约
    saveAppointmentBtn.addEventListener('click', () => {
        saveAppointment();
    });

    // 导出数据
    exportBtn.addEventListener('click', () => {
        exportAppointments();
    });

    // 搜索按钮
    searchBtn.addEventListener('click', () => {
        searchAppointments();
    });

    // 状态筛选变化
    statusFilter.addEventListener('change', () => {
        filterAppointments();
    });

    // 科室筛选变化
    departmentFilter.addEventListener('change', () => {
        filterAppointments();
    });

    // 日期筛选变化
    dateFilter.addEventListener('change', () => {
        filterAppointments();
    });

    // 打开预约详情模态框
    function openAppointmentModal(item = null) {
        // 重置表单
        document.getElementById('appointmentForm').reset();
        
        // 如果传入了预约项，填充表单数据
        if (item) {
            const patientName = item.querySelector('.appointment-patient').textContent;
            const appointmentType = item.querySelector('.appointment-type').textContent.split(' - ')[0];
            const department = item.querySelector('.appointment-type').textContent.split(' - ')[1];
            const timeText = item.querySelector('.appointment-time').textContent;
            
            document.getElementById('patientName').value = patientName;
            
            // 设置预约类型
            const typeSelect = document.getElementById('appointmentType');
            for (let i = 0; i < typeSelect.options.length; i++) {
                if (typeSelect.options[i].text === appointmentType) {
                    typeSelect.selectedIndex = i;
                    break;
                }
            }
            
            // 设置科室
            const departmentSelect = document.getElementById('appointmentDepartment');
            for (let i = 0; i < departmentSelect.options.length; i++) {
                if (departmentSelect.options[i].text === department) {
                    departmentSelect.selectedIndex = i;
                    break;
                }
            }
            
            // 设置状态
            if (item.classList.contains('confirmed')) {
                document.getElementById('appointmentStatus').value = 'confirmed';
            } else if (item.classList.contains('pending')) {
                document.getElementById('appointmentStatus').value = 'pending';
            } else if (item.classList.contains('completed')) {
                document.getElementById('appointmentStatus').value = 'completed';
            } else if (item.classList.contains('canceled')) {
                document.getElementById('appointmentStatus').value = 'canceled';
            }
        }
        
        // 显示模态框
        appointmentModal.style.display = 'flex';
    }

    // 关闭预约详情模态框
    function closeAppointmentModal() {
        appointmentModal.style.display = 'none';
    }

    // 保存预约
    function saveAppointment() {
        // 获取表单数据
        const patientName = document.getElementById('patientName').value;
        const appointmentType = document.getElementById('appointmentType').selectedOptions[0].text;
        const department = document.getElementById('appointmentDepartment').selectedOptions[0].text;
        const doctor = document.getElementById('appointmentDoctor').selectedOptions[0].text;
        const status = document.getElementById('appointmentStatus').value;
        const date = document.getElementById('appointmentDate').value;
        const time = document.getElementById('appointmentTime').value;
        const notes = document.getElementById('appointmentNotes').value;
        
        // 数据校验
        if (!patientName || !date || !time) {
            alert('请填写必填字段');
            return;
        }
        
        // 在实际应用中，这里应该发送请求到后端保存数据
        console.log('Saving appointment:', {
            patientName,
            appointmentType,
            department,
            doctor,
            status,
            date,
            time,
            notes
        });
        
        // 模拟成功保存
        alert('预约保存成功');
        closeAppointmentModal();
        
        // 在实际应用中，这里应该刷新预约数据
    }

    // 导出预约数据
    function exportAppointments() {
        // 在实际应用中，这里应该请求后端导出数据
        alert('预约数据导出功能将在后端实现');
    }

    // 搜索预约
    function searchAppointments() {
        // 获取筛选条件
        const date = dateFilter.value;
        const status = statusFilter.value;
        const department = departmentFilter.value;
        
        // 在实际应用中，这里应该请求后端搜索数据
        console.log('Searching appointments:', { date, status, department });
        alert('搜索功能将在后端实现');
    }

    // 筛选预约
    function filterAppointments() {
        // 获取筛选条件
        const date = dateFilter.value;
        const status = statusFilter.value;
        const department = departmentFilter.value;
        
        // 在实际应用中，这里应该根据筛选条件过滤本地数据或请求后端
        console.log('Filtering appointments:', { date, status, department });
    }

    // 工具函数：格式化日期范围
    function formatDateRange(start, end) {
        const options = { year: 'numeric', month: 'long', day: 'numeric' };
        return `${start.toLocaleDateString('zh-CN', options)} - ${end.toLocaleDateString('zh-CN', options)}`;
    }

    // 工具函数：格式化星期名称
    function formatDayName(dayIndex) {
        const dayNames = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
        return dayNames[dayIndex];
    }

    // 工具函数：格式化日期（月日）
    function formatDayDate(date) {
        return `${date.getMonth() + 1}月${date.getDate()}日`;
    }

    // 工具函数：判断是否是同一天
    function isSameDay(date1, date2) {
        return date1.getFullYear() === date2.getFullYear() &&
               date1.getMonth() === date2.getMonth() &&
               date1.getDate() === date2.getDate();
    }

    // 初始化页面
    updateCalendarView();
}); 